<template>
  <div class="border-t border-gray-200 pt-6">
    <h3 class="text-lg font-semibold text-gray-900 mb-4">语音配置</h3>

    <div class="space-y-4">
      <!-- 选择音色 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">角色音色</label>
        <div class="flex items-center gap-3">
          <div class="flex-1">
            <select
              :value="modelValue"
              @change="onChange"
              class="w-full h-10 px-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#635BFF] focus:border-transparent"
            >
              <!-- <option value="">请选择音色</option> -->
              <optgroup label="系统音色" v-if="systemVoices.length">
                <option v-for="v in systemVoices" :key="v" :value="v">{{ v }}</option>
              </optgroup>
              <optgroup label="自定义音色" v-if="customVoices.length">
                <option v-for="v in customVoices" :key="v" :value="v">{{ v }}</option>
              </optgroup>
            </select>
          </div>
          <button
            type="button"
            class="h-10 px-4 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors flex items-center gap-2 disabled:opacity-50"
            :disabled="!modelValue"
            @click="$emit('preview')"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 4.663 12 5.109 12 6v12c0 .891-1.077 1.337-1.707.707L5.586 15z" />
            </svg>
            试听
          </button>
        </div>
      </div>

      <!-- 自定义音色 -->
      <div class="p-4 rounded-lg ring-1 ring-gray-200 bg-white">
        <div class="text-sm font-medium text-gray-900 mb-2">自定义音色</div>
        <div class="space-y-3">
          <div class="flex items-center gap-3 flex-wrap">
            <input
              ref="fileInput"
              type="file"
              accept=".mp3,.wav"
              @change="handleFileSelect"
              class="hidden"
            />
            <button 
              type="button" 
              class="h-9 px-3 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition disabled:opacity-50"
              :disabled="isUploading"
              @click="triggerFileUpload"
            >
              {{ isUploading ? '上传中...' : '上传音频' }}
            </button>
            <span class="text-xs text-gray-400">支持 mp3/wav</span>
          </div>
          
          <!-- 上传成功后显示音色ID和试听按钮 -->
          <!-- <div v-if="customVoiceId" class="flex items-center gap-3">
            <div class="flex-1">
              <input
                :value="customVoiceId"
                readonly
                class="w-full h-10 px-3 border border-gray-200 rounded-lg bg-gray-50 text-sm"
                placeholder="音色ID"
              />
            </div>
            <button
              type="button"
              class="h-10 px-4 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors flex items-center gap-2"
              @click="previewCustomVoice"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 4.663 12 5.109 12 6v12c0 .891-1.077 1.337-1.707.707L5.586 15z" />
              </svg>
              试听
            </button>
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { characterInfo } from '@/api'

const props = defineProps<{ modelValue: string }>()
const emit = defineEmits<{ 'update:modelValue': [val: string]; preview: [] }>()

const systemVoices = ref<string[]>([])
const customVoices = ref<string[]>([])
const loading = ref(false)

// 自定义音色相关状态
const fileInput = ref<HTMLInputElement>()
const isUploading = ref(false)
const customVoiceId = ref<string>('')

async function fetchVoices() {
  try {
    loading.value = true
    const res: any = await characterInfo.voices()
    // 兼容不同返回结构：{code:0, data:[...]} 或 直接数组
    const list: string[] = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : []
    systemVoices.value = list
  } catch (e) {
    // 忽略错误，保持为空
  } finally {
    loading.value = false
  }
}

function onChange(e: Event) {
  const target = e.target as HTMLSelectElement
  emit('update:modelValue', target.value)
}

// 触发文件选择
function triggerFileUpload() {
  fileInput.value?.click()
}

// 处理文件选择
async function handleFileSelect(e: Event) {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.includes('audio/') && !file.name.match(/\.(mp3|wav)$/i)) {
    alert('请选择 mp3 或 wav 格式的音频文件')
    return
  }

  // 检查文件大小（限制为10MB）
  if (file.size > 10 * 1024 * 1024) {
    alert('文件大小不能超过 10MB')
    return
  }

  try {
    isUploading.value = true
    const res = await characterInfo.uploadVoice(file)
    
    // 处理返回结果，假设后端返回 { code: 0, data: { voiceId: 'xxx' } } 或直接返回音色ID
    let voiceId = ''
    if (res?.data?.voiceId) {
      voiceId = res.data.voiceId
    } else if (typeof res === 'string') {
      voiceId = res
    } else if ((res as any)?.voiceId) {
      voiceId = (res as any).voiceId
    }

    if (voiceId) {
      customVoiceId.value = voiceId
      // 将自定义音色添加到选项中
      customVoices.value.push(voiceId)
      // 自动选择新生成的音色
      emit('update:modelValue', voiceId)
      alert('音色生成成功！')
    } else {
      alert('音色生成失败，请重试')
    }
  } catch (error) {
    console.error('上传音频失败:', error)
    alert('上传失败，请重试')
  } finally {
    isUploading.value = false
    // 清空文件输入
    if (target) target.value = ''
  }
}

// 试听自定义音色 - 复用角色音色的试听逻辑
function previewCustomVoice() {
  if (!customVoiceId.value) return
  
  // 临时设置modelValue为自定义音色ID，触发角色音色试听
  const originalValue = props.modelValue
  emit('update:modelValue', customVoiceId.value)
  
  // 触发角色音色试听
  emit('preview')
  
  // 恢复原始值
  setTimeout(() => {
    emit('update:modelValue', originalValue)
  }, 100)
}

onMounted(fetchVoices)
</script>


